package cn.cqone.crm.controller;


import cn.cqone.crm.domain.Tenant;
import cn.cqone.crm.query.TenantQuery;
import cn.cqone.crm.service.TenantService;
import cn.cqone.crm.twoObject.TwoSimple;
import cn.cqone.crm.utils.JSONResult;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

@Controller
@ResponseBody
@RequestMapping("/tenant")
@CrossOrigin
@RequiresPermissions("tenant:main")
public class TenantController extends BaseController<Tenant,Long, TenantQuery>{
    @Autowired
    private TenantService tenantService;

    //租户注册
    @RequestMapping(value = "/settleIn",method = RequestMethod.POST)
    public JSONResult settleIn(@RequestBody TwoSimple twoSimple){
        try{
            tenantService.settleIn(twoSimple);

            return JSONResult.ok("注册成功");

        }catch (Exception e){
            e.printStackTrace();
            return JSONResult.error("服务器异常,我们正在殴打程序员...");
        }
    }
    //添加
    @RequiresPermissions("")
    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public JSONResult upload(MultipartFile file, HttpServletRequest request) throws Exception {
        //扩展名
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        //生成文件名
        String filePath = "upload/"+ UUID.randomUUID().toString().replaceAll("-","")+"."+extension;
        //保存路径
        String savePath = ContextLoader.getCurrentWebApplicationContext().getServletContext().getRealPath("/")+filePath;
        //把文件写到磁盘
        createFile(savePath);

        IOUtils.copy(file.getInputStream(),new FileOutputStream(savePath));
        return JSONResult.ok(filePath);
    }
    private void createFile(String savePath) throws IOException {
        File file = new File(savePath);
        if(!file.exists()){
            if(!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
                System.out.println(file.getAbsolutePath());
            }
            file.createNewFile();
        }
    }
}
